# !/usr/bin/env python
# -*- encoding: utf-8 -*-

class Resultchange():
    def resultchange(self, params, final_results):  # 请求参数中关联参数替换成关联参数拆分结果列的取值
        final_results = str(final_results)
        final_results = eval(final_results)  # 转成字典类型
        for keyword in final_results:
            if str(params).find(keyword) > 0:
                params = str(params).replace(keyword, str(final_results[keyword]))
                params = eval(params)
        return params

    def resultchangeurl(self, rl, final_results):  # 请求url中关联参数替换成关联参数拆分结果列的取值
        final_results = eval(str(final_results))
        import re
        rlNew = re.split('[/?]', rl)
        for keyword in final_results.keys():
            for i in range(len(rlNew)):
                if rlNew[i] == keyword:
                    rlNew[i] = str(final_results[keyword])
        rlNew2 = '/'.join(rlNew)
        if '?' in rl:
            rlNew3 = self.rreplace(rlNew2, '/', '?', 1)
            return rlNew3
        else:
            return rlNew2

    # 字符串从右往左替换
    def rreplace(self, data, old, new, *max):
        count = len(data)
        if max and str(max[0]).isdigit():
            count = max[0]
        return new.join(data.rsplit(old, count))


if __name__ == "__main__":
    rl = '/loyalty2-mg/1.0/member/members/320013/${memberId}/points/324405/records/handle/gain'
    final_results = {'${planId}': 320013}
    print(Resultchange().resultchangeurl(rl, final_results))
